package com.restfinder.restaurant.component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.restfinder.restaurant.model.Restaurant;

@Slf4j
public class GeolocalizationUtils {

	// URL prefix to the geocoder
	private static final String GEOCODER_REQUEST_PREFIX_FOR_JSON = "http://maps.google.com/maps/api/geocode/json";
	public static final String LONGITUDE_MAP_KEY = "longitude";
	public static final String LATTITUDE_MAP_KEY = "lattitude";

	public static Map<String, Double> getLocalization(String address) {
		Map<String, Double> returnMap = new HashMap<String, Double>();
		try {
			log.debug("address: " + address);
			// query address
			HttpClient httpclient = new DefaultHttpClient();
			String url = GEOCODER_REQUEST_PREFIX_FOR_JSON + "?address="
					+ URLEncoder.encode(address, "UTF-8") + "&sensor=true";
			log.debug("url: " + url);
			HttpPost httppost = new HttpPost(url);

			InputStream is = null;
			String result = null;

			is = httpclient.execute(httppost).getEntity().getContent();

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
			JSONObject response = new JSONObject(result);
			String temp = response.getString("status");
			if (temp.equals("OK")) {
				JSONArray jArray = new JSONArray(response.getString("results"));
				JSONObject json_data = jArray.getJSONObject(0);
				JSONObject geometry = json_data.getJSONObject("geometry");
				JSONObject location = geometry.getJSONObject("location");
				returnMap.put(LATTITUDE_MAP_KEY, location.getDouble("lat"));
				returnMap.put(LONGITUDE_MAP_KEY, location.getDouble("lng"));
			}
			return returnMap;
		} catch (Exception e) {
			log.error("Error while retrieving geolocalization", e);
			e.printStackTrace();
			returnMap.put(LATTITUDE_MAP_KEY, 0.0);
			returnMap.put(LONGITUDE_MAP_KEY, 0.0);
			return returnMap;
		}
	}
}
